const {postLogData} =require("../utils/misc")
const router = require('koa-router')(); //引入router 并调用
const ObjectId = require('mongodb').ObjectId
const mongo = require('../compents/mongo')

// 设置根路径
router.prefix('/aboutUs')

// 测试用端口
router.get('/test', async ctx => {
    console.log(ctx);
    ctx.body = 'test'
})

// 获取后台数据
router.get('/list', async ctx => {
    postLogData("请求关于我们")
    let { limit, page, where } = ctx.query
    const res = await mongo.find('aboutUs', { limit: limit * 1, page: page * 1 })
    const total = await mongo.count('aboutUs', { where })
    ctx.body = { data: res, code: 20000, total, message: "端口求成功" }
})

// 保存数据
router.post('/save', async ctx => {
    postLogData("新增关于我们")
    const res = await mongo.insertOne('aboutUs', {...ctx.request.body })
    if (res.insertedId) {
        ctx.body = { data: res, code: 20000, message: "数据插入成功" };
    } else {
        ctx.body = { data: res, code: 50001, message: "数据插入失败" };
    }
})

// 修改数据
router.post('/change', async ctx => {
    postLogData("修改关于我们")
    const { _id } = ctx.request.body
    const update = ctx.request.body
    delete update._id
    const res = await mongo.updateOne('aboutUs', { where: { _id: ObjectId(_id) }, update })
    if (res.modifiedCount > 0) {
        ctx.body = { data: res, code: 20000, message: "数据修改成功" };
    } else {
        ctx.body = { data: res, code: 50002, message: "数据修改失败" };
    }

})


module.exports = router //导出路由对象